import { Component, OnInit } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { JsonApiService } from 'app/core/api/json-api.service'
// import { ThrowStatement } from 'typescript'
import { config } from '../../shared/smartadmin.config'

declare var $: any
declare var Viewer: any
@Component({
  selector: 'sa-user-page',
  templateUrl: './invoice-apply-page.component.html',
  styleUrls: ['./invoice-apply-page.component.css']
})
export class InvoiceApplyPageComponent implements OnInit {
  validatorOptions = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      // name: {
      //   validators: {
      //     notEmpty: {
      //       message: '请输入申请人姓名'
      //     }
      //   }
      // },
      // phone: {
      //   validators: {
      //     notEmpty: {
      //       message: '请输入申请人手机号'
      //     }
      //   }
      // },
      factoryName: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择所属项目'
          }
        }
      },
      money: {
        validators: {
          callback: {
            callback: function (value, validator, $field) {
              if (value) {
                let isValid = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{2})))$/.test(value)
                if (isValid) {
                  if (value > 9999999.99) {
                    return {
                      valid: false,
                      message: '金额不能超过1千万'
                    }
                   } else {
                    return true
                  }
                } else {
                  return {
                    valid: false,
                    message: '请输入正整数并且小数点后面只能保留两位小数'
                  }
                }
              } else {
                return {
                  valid: false,
                  message: '请输入金额'
                }
              }
            }.bind(this)
          }
        }
      },
      typeExpense: {
        validators: {
          notEmpty: {
            message: '请选择费用类型'
          }
        }
      },
      remark: {
        validators: {
          notEmpty: {
            message: '请输入备注'
          }
        }
      },
      headName: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择企业名称'
          }
        }
      },
      dutyParagraph: {
        validators: {
          notEmpty: {
            message: '请输入税号'
          }
        }
      }
    }
  }

  validatorOptionsDynamic = {
    bankName: {
      validators: {
        notEmpty: {
          message: '请输开户银行'
        }
      }
    },
    bankAccount: {
      validators: {
        callback: {
          callback: function (value, validator, $field) {
            if (value) {
              let isValid1 = /^[0-9]*[1-9][0-9]*$/.test(value)
              if (isValid1 && value.length <= 30) {
                return true
              } else {
                return {
                  valid: false,
                  message: '请输入正确的银行卡号'
                }
              }
            } else {
              return {
                valid: false,
                message: '请输入银行卡号'
              }
            }
          }.bind(this)
        }
      }
    },
    companyAddress: {
      validators: {
        notEmpty: {
          message: '请输入注册地址'
        }
      }
    },
    companyPhone: {
      validators: {
        notEmpty: {
          message: '请输入注册号码'
        }
      }
    },
    shippingName: {
      trigger: 'change',
      validators: {
        notEmpty: {
          message: '请输入收货人姓名'
        }
      }
    },
    shippingPhone: {
      validators: {
        callback: {
          callback: function (value, validator, $field) {
            if (value) {
              let isValid1 = /([0-9]{3,4}-)?[0-9]{7,8}/.test(value)
              let isValid2 =
                /^((\+?86)|(\(\+86\)))?(13[012356789][0-9]{8}|15[012356789][0-9]{8}|18[02356789][0-9]{8}|147[0-9]{8}|1349[0-9]{7})$/.test(
                  value
                )
              if (value.indexOf('-') != -1) {
                if (isValid1) {
                  return true
                } else {
                  return {
                    valid: false,
                    message: '请输入正确手机号码'
                  }
                }
              } else {
                if (isValid2) {
                  return true
                } else {
                  return {
                    valid: false,
                    message: '请输入正确手机号码'
                  }
                }
              }
            } else {
              return {
                valid: false,
                message: '请输入手机号码'
              }
            }
          }.bind(this)
        }
      }
    },
    address: {
      validators: {
        notEmpty: {
          message: '请输入收货人详细地址'
        }
      }
    },
    provinceId: {
      validators: {
        notEmpty: {
          message: '请选择省份名称'
        }
      }
    },
    cityId: {
      validators: {
        notEmpty: {
          message: '请选择城市名称'
        }
      }
    },
    townId: {
      validators: {
        notEmpty: {
          message: '请选择区域名称'
        }
      }
    },
    userEmail: {}
  }

  curPage: number = 0 //缓存页码使用

  page: any = {
    id: '',
    name: '', // 申请人姓名
    phone: '', // 申请人姓名
    factoryId: '',
    factoryName: '', // 所属项目名称 (顶级)
    invoiceType: 0, // 发票类型(0.纸质发票；1.电子发票(普票)；2.电子发票(专票))
    money: '', // 开票金额 单位分
    typeExpense: '', // 费用类型（1:安装费  2:维修费  3:服务续费 4. 对接费
    remark: '', // 备注
    certificateUrlListJson: '', // 备注
    headName: '', // 发票抬头名称
    dutyParagraph: '', // 税号
    companyAddress: '', // 公司地址
    companyPhone: '', // 公司电话
    bankName: '', // 开户行
    bankAccount: '', // 开票银行账户
    shippingName: '', // 收货人姓名
    shippingPhone: '', // 收货人电话
    address: '', // 收货人详细地址
    provinceId: '', // 省
    provinceName: '', // 省份名称
    cityId: '', // 城市id
    cityName: '', // 城市名称
    townId: '', // 区id
    townName: '', // 区名称
    userEmail: '', // 电子邮箱
    system: 1 // 平台标识：0-小程序，1-WEB
  }

  pageType: string = 'new'

  companyParentList: any = [] //公司树的存储值

  invoiceTypeList: any = [
    {
      text: '纸质发票(专票)',
      value: 0
    },
    {
      text: '电子发票(普票)',
      value: 1
    },
    {
      text: '电子发票(专票)',
      value: 2
    }
  ]

  typeExpenseList: any = [
    {
      value: 1,
      text: '安装费'
    },
    {
      value: 2,
      text: '维修费'
    },
    {
      value: 3,
      text: '服务续费'
    },
    {
      value: 4,
      text: '对接费'
    }
  ]

  areaData: any = [] //省市县数据
  provinceNameArr: any = [] //省数据
  cityNameArr: any = [] //城市数据
  townNameArr: any = [] //县数据

  constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.page.id = queryParams.id
      this.pageType = queryParams.type
      this.curPage = queryParams.nowPage
    })
  }

  async ngOnInit() {
    await this.ngInitdata()
    this.ngInitCompany()

    System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
      System.import('assets/js/select2-zh-CN.js').then(() => {
        this.initCompany()
        this.initShippingSelect()
        if (this.pageType === 'update') {
          this.editInit()
        } else {
          this.dynamicUpdateValidatorOptions(true)
        }
      })
    })
  }
  // 编辑回显
  editInit() {
    let reqdata = 'id=' + this.page.id
    this.jsonApiService.http('invoice/queryById.html', reqdata).subscribe(data => {
      if (data.success) {
        for (let item in this.page) {
          this.page[item] = data.data[item]
        }
        this.page.name = data.data.nickName ? data.data.nickName : data.data.name
        this.page.money = data.data.money / 100
        if (data.data.certificateUrls && data.data.certificateUrls.length) {
          this.imageInfo.imageList = data.data.certificateUrls
        }
        this.dynamicUpdateValidatorOptions(true)
        // 企业名称
        var str = $("<span class='select2-selection__rendere'>" + data.data.headName + '</span>')
        $('#companySelect').val('')
        $('#select2-companySelect-container').empty()
        $('#select2-companySelect-container').attr('title', '')
        $('#select2-companySelect-container').prepend(str)
        //收货人姓名
        var str = $("<span class='select2-selection__rendere'>" + data.data.shippingName + '</span>')
        $('#shippingSelect').val('')
        $('#select2-shippingSelect-container').empty()
        $('#select2-shippingSelect-container').attr('title', '')
        $('#select2-shippingSelect-container').prepend(str)
        // 省市区
        this.provinceChange(this.page.provinceId, false)
        this.cityChange(this.page.cityId, false)
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }
  //表单提交
  onSubmit() {
    // const roleValue = $("#roleSelect2").val();
    $('#applyInvoiceForm').bootstrapValidator('validate') //开启验证
    let isValid = $('#applyInvoiceForm').data('bootstrapValidator').isValid() //验证是否通过
    if (isValid) {
      var reqdata = new FormData()
      var url = 'invoice/applyInvoiceForWeb.html'
      if (this.pageType === 'update') {
        url = 'invoice/update.html'
      }
      let pageValue =  this.page
      pageValue.certificateUrlListJson = JSON.stringify(this.imageInfo.imageList)
      if (pageValue.invoiceType === 0) {
        delete pageValue.userEmail
      } else {
        delete pageValue.shippingName
        delete pageValue.shippingPhone
        delete pageValue.address
        delete pageValue.provinceId
        delete pageValue.provinceName
        delete pageValue.cityId
        delete pageValue.cityName
        delete pageValue.townId
        delete pageValue.townName
      }
      for (let item in pageValue) {
        if (item === 'money') {
          let money = Number(pageValue[item]) as number
          reqdata.append(item, `${money * 100}`)
        } else {
          reqdata.append(item, pageValue[item])
        }
      }

      this.jsonApiService.form_http(url, reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.router.navigate(['/contract/Invoice'], {
            queryParams: {
              nowPage: this.curPage
            }
          })
        }
      })
    }
  }

  //返回资源列表页
  goBack() {
    this.router.navigate(['/contract/Invoice'], {
      queryParams: {
        nowPage: this.curPage
      }
    })
  }
  //拉取省市县数据
  ngInitdata() {
    return new Promise(
      function (resolve, reject) {
        this.jsonApiService.http('company/regionList.html', null).subscribe(data => {
          if (data.message) {
            this.areaData = data.data
            for (let item of this.areaData) {
              if (item.level === 2) {
                this.provinceNameArr.push(item)
              }
            }
            resolve()
          } else {
            this.jsonApiService.message(data.message)
            reject()
          }
        })
      }.bind(this)
    )
  }

  //父级公司树请求
  ngInitCompany() {
    this.jsonApiService.http('company/companytree.html', null).subscribe(data => {
      this.companyParentList = data
    })
  }

  //省份change回调事件
  provinceChange(e, isReset = true) {
    this.cityNameArr = []
    this.townNameArr = []
    this.page.provinceId = e
    for (let provinceIndex = 0; provinceIndex < this.provinceNameArr.length; provinceIndex++) {
      if (this.provinceNameArr[provinceIndex].id === e) {
        this.page.provinceName = this.provinceNameArr[provinceIndex].areaName
      }
    }
    for (let item of this.areaData) {
      if (this.page.provinceId === item.parentId) {
        this.cityNameArr.push(item)
      }
    }
    if (isReset === true) {
      this.page.cityId = ''
      this.page.cityName = ''
      this.page.townId = ''
      this.page.townName = ''
    }
  }
  //城市change回调事件
  cityChange(e, isReset = true) {
    this.townNameArr = []
    this.page.cityId = e
    for (let index = 0; index < this.cityNameArr.length; index++) {
      if (this.cityNameArr[index].id === e) {
        this.page.cityName = this.cityNameArr[index].areaName
      }
    }
    for (let item of this.areaData) {
      if (this.page.cityId === item.parentId) {
        this.townNameArr.push(item)
      }
    }
    if (isReset === true) {
      this.page.townId = ''
      this.page.townName = ''
    }
  }
  townChange(e) {
    this.page.townId = e
    for (let index = 0; index < this.townNameArr.length; index++) {
      if (this.townNameArr[index].id === e) {
        this.page.townName = this.townNameArr[index].areaName
      }
    }
  }

  //新增或者编辑公司选中回调
  addCompanySelected2(data) {
    this.page.factoryId = data.companyId || ''
    this.page.factoryName = data.companyName
    $('#factoryName').val(data.companyName).change()
  }

  //初始化企业名称
  initCompany() {
    var that = this
    $('#companySelect')
      .select2({
        language: 'zh-CN',
        minimumInputLength: 2,
        allowClear: true,
        placeholder: '请选择',
        ajax: {
          url: config.BaseURL + 'invoiceHead/queryEnterpriseV2.html',
          dataType: 'json',
          delay: 50,
          method: 'POST',
          xhrFields: { withCredentials: true },
          data: function (params) {
            return { searchKey: params.term }
          },
          processResults: function (data, params) {
            var options = new Array()
            $(data.data).each(function (index, data) {
              options.push({
                id: data.taxNo,
                text: `${data.enterpriseName}(${data.taxNo})`,
                headName: data.enterpriseName,
                dutyParagraph: data.taxNo,
                companyAddress: data.address,
                bankName: data.bankName,
                bankAccount: data.bankNo,
                companyPhone: data.tel
              })
            })

            const date = Date.parse(`${new Date()}`)
            options.unshift({ text: params.term, headName: params.term, id: `${date}`, isNew: true })

            return {
              results: options //获取查询后的结果
            }
          },
          cache: true
        },
        templateResult: function (state) {
          if (!state.id) {
            return state.text
          }
          var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>')
          return $state
        }
      })
      .on('select2:select', function (e) {
        var data = e.params.data
        that.page.headName = data.headName
        if (!data.isNew) {
          that.page.dutyParagraph = data.dutyParagraph
          that.page.companyAddress = data.companyAddress
          that.page.bankName = data.bankName
          that.page.bankAccount = data.bankAccount
          that.page.companyPhone = data.companyPhone
          $('#applyInvoiceForm').data('bootstrapValidator').resetForm()
        }
        $('#headName').val(that.page.headName).change()
      })
  }

  //初始收货地址
  initShippingSelect() {
    var that = this
    $('#shippingSelect')
      .select2({
        language: 'zh-CN',
        minimumInputLength: 2,
        allowClear: true,
        placeholder: '请选择',
        ajax: {
          url: config.BaseURL + 'shippingAddress/queryAddress.html',
          dataType: 'json',
          delay: 50,
          method: 'POST',
          xhrFields: { withCredentials: true },
          data: function (params) {
            return { searchKey: params.term }
          },
          processResults: function (data, params) {
            var options = new Array()
            $(data.data).each(function (index, car) {
              options.push({
                id: car.id,
                text: `${car.shippingName}(${car.shippingPhone})`,
                shippingName: car.shippingName,
                provinceId: car.provinceId,
                provinceName: car.provinceName,
                townName: car.townName,
                townId: car.townId,
                cityName: car.cityName,
                cityId: car.cityId,
                address: car.address,
                shippingPhone: car.shippingPhone
              })
            })

            const date = Date.parse(`${new Date()}`)
            options.unshift({ text: params.term, id: `${date}`, shippingName: params.term, isNew: true })

            return {
              results: options
            }
          },
          cache: true
        },
        templateResult: function (state) {
          if (!state.id) {
            return state.text
          }
          var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>')
          return $state
        }
      })
      .on('select2:select', function (e) {
        var data = e.params.data
        that.page.shippingName = data.shippingName
        if (!data.isNew) {
          $('#applyInvoiceForm').data('bootstrapValidator').resetForm()
          that.page.provinceId = data.provinceId
          that.page.provinceName = data.provinceName
          that.page.townName = data.townName
          that.page.townId = data.townId
          that.page.cityName = data.cityName
          that.page.cityId = data.cityId
          that.page.address = data.address
          that.page.shippingPhone = data.shippingPhone
          data.provinceId && that.provinceChange(data.provinceId, false)
          data.cityId && that.cityChange(data.cityId, false)
        }
        $('#shippingName').val(that.page.shippingName).change()
      })
  }

  typeChange(value) {
    this.page.typeExpense = value
  }
  invoiceTypeChange(value) {
    this.page.invoiceType = value
    $('#applyInvoiceForm').data('bootstrapValidator').resetForm()
    this.dynamicUpdateValidatorOptions()
  }

  dynamicUpdateValidatorOptions(isFirst = false) {
    if (this.page.invoiceType == 0 || this.page.invoiceType == 2) {
      for (const key in this.validatorOptionsDynamic) {
        const item = this.validatorOptionsDynamic[key]
        $('#applyInvoiceForm').bootstrapValidator('addField', key, item)
        // $('#applyInvoiceForm').data('bootstrapValidator').updateStatus(key, 'NOT_VALIDATED', null).validateField(key)
      }
      if (this.page.invoiceType == 0) {
        $('#applyInvoiceForm').bootstrapValidator('removeField', 'userEmail')
      } else {
        $('#applyInvoiceForm').bootstrapValidator('addField', 'userEmail', {
          validators: {
            callback: {
              callback: function (value, validator, $field) {
                if (value) {
                  let isValid1 = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value)
                  if (isValid1) {
                    return true
                  } else {
                    return {
                      valid: false,
                      message: '请输入正确的电子邮箱'
                    }
                  }
                } else {
                  return {
                    valid: false,
                    message: '请输入电子邮箱'
                  }
                }
              }.bind(this)
            }
          }
        })
        $('#applyInvoiceForm').bootstrapValidator('removeField', 'shippingName')
        $('#applyInvoiceForm').bootstrapValidator('removeField', 'shippingPhone')
        $('#applyInvoiceForm').bootstrapValidator('removeField', 'address')
        $('#applyInvoiceForm').bootstrapValidator('removeField', 'provinceId')
        $('#applyInvoiceForm').bootstrapValidator('removeField', 'cityId')
        $('#applyInvoiceForm').bootstrapValidator('removeField', 'townId')
      }

    } else {
      for (const key in this.validatorOptionsDynamic) {
        $('#applyInvoiceForm').bootstrapValidator('removeField', key)
      }
      $('#applyInvoiceForm').bootstrapValidator('addField', 'userEmail', {
        validators: {
          callback: {
            callback: function (value, validator, $field) {
              if (value) {
                let isValid1 = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value)
                if (isValid1) {
                  return true
                } else {
                  return {
                    valid: false,
                    message: '请输入正确的电子邮箱'
                  }
                }
              } else {
                return {
                  valid: false,
                  message: '请输入电子邮箱'
                }
              }
            }.bind(this)
          }
        }
      })
    }
    if (isFirst) {
      $('#applyInvoiceForm').data('bootstrapValidator').resetForm()
    }
  }

  // 图片查看
  imageInfo: any = {
    imageList: [],
    describe: 'other'
  }

  fileList: File = null
  //上传多张
  multifileChange(files: FileList) {
    if (this.isViewer && $('.viewer-container').length > 0) {
      this.viewer.destroy()
    }
    let multfileList = files
    var reqdata = new FormData()
    reqdata.append('describe', this.imageInfo.describe)
    reqdata.append('businessType', '3')
    reqdata.append('type', '2') //type 1获取相对路径  2获取绝对路径
    for (var i = 0; i < multfileList.length; i++) {
      this.fileList = multfileList[i]
      const isJPG =
        this.fileList.type === 'image/jpeg' || this.fileList.type === 'image/jpg' || this.fileList.type === 'image/png'
      const isLt4M = this.fileList.size / 1024 < 1024 * 4
      if (!isJPG) {
        this.jsonApiService.message('上传图片只能是 png, jpg, jpeg 格式!')
        return
      }
      if (!isLt4M) {
        this.jsonApiService.message('上传图片大小不能超过4M!')
        return
      }
      reqdata.append('files', multfileList[i])
    }
    this.jsonApiService.form_http('fileUpload/upload.html', reqdata).subscribe(data => {
      if (data.success) {
        for (var i = 0; i < data.data.length; i++) {
          this.imageInfo.imageList.push(data.data[i])
        }
      }
    })
    for (let k = 0; k < $('.up').length; k++) {
      $('.up')[k].value = null
    }
  }

  //删除图片
  deleteImg(index, i) {
    if (index == 1) {
      this.imageInfo.imageList.splice(i, 1)
    }
    if (this.isViewer && $('.viewer-container').length > 0) {
      this.viewer.destroy()
    }
  }

  //图片放大
  isViewer: Boolean = false
  viewer: any
  bigimg(ele) {
    if (this.isViewer && $('.viewer-container').length > 0) {
      this.viewer.destroy()
      System.import('assets/js/viewer/viewer.js').then(() => {
        System.import('assets/js/viewer/bootstrap.bundle.min.js').then(() => {
          System.import('assets/js/viewer/viewer.css').then(() => {
            this.showImg(ele)
          })
        })
      })
    } else {
      this.showImg(ele)
    }
  }
  showImg(ele) {
    var that = this
    var imgList = $('.' + ele)[0]
    this.viewer = new Viewer(imgList, {
      url: 'src',
      title: function (image) {
        return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')'
      }
    })
    this.isViewer = true
  }
}
